package com.shoplink.launcher;

import java.lang.reflect.Field;

import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.EthernetManager;
import android.net.IpConfiguration;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.shoplink.view.IPSettingView;

public class EthSettings extends Fragment {
	private final static String TAG = "cedar";
	private View ipAddressLine, subnetMaskLine, gatewayLine, dnsAddressLine;
	private TextView ipAddressText, subnetMaskText, gatewayText,
			dnsAddressText;
	private IpConfiguration mEthInfo;
	private EthernetManager mEthManager;
	private static final boolean ENABLE_PROXY = true;
	/* These values come from "wifi_proxy_settings" resource array */
	public static final int PROXY_NONE = 0;
	public static final int PROXY_STATIC = 1;
	private IntentFilter mFilter;
	private BroadcastReceiver mReceiver;
	private boolean isFromSetting = false;
	private final int GET_DHCP_IP_MSG = 0x008;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	private void handleEvent(Intent intent) {
		String action = intent.getAction();
		if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
			if (!isFromSetting
					&& NetworkUtils.isNetworkConnected(getActivity())) {
			}
		}
	}

	@Override
	public void onDetach() {
		super.onDetach();

		try {
			Field childFragmentManager = Fragment.class
					.getDeclaredField("mChildFragmentManager");
			childFragmentManager.setAccessible(true);
			childFragmentManager.set(this, null);

		} catch (NoSuchFieldException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		isFromSetting = getActivity().getIntent().getBooleanExtra(
				NetworkUtils.FROM_SETTINGS, false);
		mFilter = new IntentFilter();
		mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
		mReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				handleEvent(intent);
			}
		};
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View fragmentView = inflater.inflate(R.layout.eth_settings, container,
				false);
		mEthManager = (EthernetManager) getActivity().getSystemService(
				Context.ETHERNET_SERVICE);
		ipAddressLine = fragmentView.findViewById(R.id.ip_address_line);
		subnetMaskLine = fragmentView.findViewById(R.id.subnet_mask_line);
		gatewayLine = fragmentView.findViewById(R.id.gateway_line);
		dnsAddressLine = fragmentView.findViewById(R.id.dns_address_line);
		// ipAddressEditor.addTextChangedListener(textWatcher);

		ipAddressText = (TextView) fragmentView
				.findViewById(R.id.ip_address_text);
		subnetMaskText = (TextView) fragmentView
				.findViewById(R.id.subnet_mask_text);
		gatewayText = (TextView) fragmentView.findViewById(R.id.gateway_text);
		dnsAddressText = (TextView) fragmentView
				.findViewById(R.id.dns_address_text);
		updateViews(false);
		return fragmentView;
	}

	@Override
	public void onResume() {
		getActivity().registerReceiver(mReceiver, mFilter);
		mEthInfo = mEthManager.getConfiguration();

		// if (mEthInfo.getConnectMode()
		// .equals(EthernetDevInfo.ETH_CONN_MODE_DHCP)) {
		// mSwitch.setChecked(false);
		// updateViews(false);
		// } else {
		// mSwitch.setChecked(true);
		// updateViews(true);
		// }
		super.onResume();
	}

	@Override
	public void onPause() {
		getActivity().unregisterReceiver(mReceiver);
		super.onPause();
	}

	public void updateViews(boolean checked) {
		handler.sendEmptyMessage(GET_DHCP_IP_MSG);
	}

	public String getEthGateWay() {
		ConnectivityManager conn = (ConnectivityManager) getActivity()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		String ip = conn.getLinkProperties(ConnectivityManager.TYPE_ETHERNET)
				.getAddresses().toString();
		String mGW = conn.getLinkProperties(ConnectivityManager.TYPE_ETHERNET)
				.getRoutes().toString();
		String mDns = conn.getLinkProperties(ConnectivityManager.TYPE_ETHERNET)
				.getDnsServers().toString();
		Log.i(TAG, "getEthGateWay ip=" + ip);
		Log.i(TAG, "getEthGateWay mGW=" + mGW);
		Log.i(TAG, "getEthGateWay mDns=" + mDns);
		if (mGW.contains(">")) {
			try {
				mGW = mGW.substring(mGW.lastIndexOf('>') + 2, mGW.length() - 1);
				mGW = mGW.split(" ")[0];
			} catch (Exception e) {
				// TODO: handle exception
			}

		}
		return mGW;
	}

	Handler handler = new Handler() {
		@SuppressWarnings("deprecation")
		public void handleMessage(android.os.Message msg) {

			String ipAddress = "";
			String netmask = "";
			String gateway = "";
			String dns1 = "";
			// DhcpInfo mDhcpInfo =
			// mEthManager.getConfiguration().getStaticIpConfiguration().;
			if (msg.what == GET_DHCP_IP_MSG) {

				ConnectivityManager conn = (ConnectivityManager) getActivity()
						.getSystemService(Context.CONNECTIVITY_SERVICE);
				ipAddress = conn
						.getLinkProperties(ConnectivityManager.TYPE_ETHERNET)
						.getAddresses().get(0).getHostAddress();
				gateway = getEthGateWay();
				dns1 = conn
						.getLinkProperties(ConnectivityManager.TYPE_ETHERNET)
						.getDnsServers().get(0).getHostAddress();

				ipAddressLine.setVisibility(View.VISIBLE);
				subnetMaskLine.setVisibility(View.VISIBLE);
				gatewayLine.setVisibility(View.VISIBLE);
				dnsAddressLine.setVisibility(View.VISIBLE);
				ipAddressText.setVisibility(View.VISIBLE);
				subnetMaskText.setVisibility(View.VISIBLE);
				gatewayText.setVisibility(View.VISIBLE);
				dnsAddressText.setVisibility(View.VISIBLE);
				ipAddressText.setText(ipAddress);
				subnetMaskText.setText(getEthernetMacAddress());
				gatewayText.setText(gateway);
				dnsAddressText.setText(dns1);

			}
		};
	};

	public String getEthernetMacAddress() {
		ConnectivityManager conn = (ConnectivityManager) getActivity()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = conn.getActiveNetworkInfo();
		if (networkInfo == null
				|| networkInfo.getType() != ConnectivityManager.TYPE_ETHERNET) {
			return "";
		} else {
			return networkInfo.getExtraInfo();
		}
	}

	// private String getLocalIpAddress() {
	// String ip;
	// try {
	// for (Enumeration<NetworkInterface> en = NetworkInterface
	// .getNetworkInterfaces(); en.hasMoreElements();) {
	// NetworkInterface intf = en.nextElement();
	// for (Enumeration<InetAddress> enumIpAddr = intf
	// .getInetAddresses(); enumIpAddr.hasMoreElements();) {
	// InetAddress inetAddress = enumIpAddr.nextElement();
	// if (!inetAddress.isLoopbackAddress()) {
	// ip = inetAddress.getHostAddress();
	// if (ip.length() > 13) {
	// continue;
	// }
	// Log.d(TAG, "==== get ip Address : " + ip);
	// return ip;
	// }
	// }
	// }
	// } catch (SocketException ex) {
	// Log.e("WifiPreference IpAddress", ex.toString());
	// }
	// return null;
	// }

}
